package com.qixuan.recommendation;

import java.util.Iterator;
import java.util.Map;

public class SimilarityCompute {

	
	
	static public Map<String, Map<String, Double>> getSimMap(){
		
	}
	
	
	static public double cosSimilarity(Map<String,String> usr1, Map<String,String> usr2){
		
		/**
		 * 注意，这里采用的算法的平均值是全集的，并非是交集。
		 * 应当另外测试交集平均值的。
		 */
		
		//计算第一个人的rating平均数
		Iterator<String> vIt1 = usr1.values().iterator();
		double rSum1 = 0;
		int count1 = 0;
		while(vIt1.hasNext()){
			
			rSum1 += Integer.valueOf(vIt1.next());
			count1++;
		}
		double rA1 = rSum1/count1;
		
		
		//计算第二个人的rating和平均数
		Iterator<String> vIt2 = usr2.values().iterator();
		double rSum2 = 0;
		int count2 = 0;
		while(vIt2.hasNext()){
			
			rSum2 += Integer.valueOf(vIt2.next());
			count2++;
		}
		double rA2 = rSum2/count2;
		

		//皮尔逊相似度的三个中间sigma和量
		double sigmaxy = 0, sigmax = 0, sigmay = 0;
		//以其中一人开始遍历
		Iterator<String> it = usr1.keySet().iterator();
		while(it.hasNext()){
			
			String mv = it.next();
			if(usr2.containsKey(mv)){
				//如果都评价过这个电影
				double r1 = Double.valueOf(usr1.get(mv));
				double r2 = Double.valueOf(usr2.get(mv));
				sigmaxy+=(r1-rA1)*(r2-rA2);
				sigmax+=(r1-rA1)*(r1-rA1);
				sigmay+=(r2-rA2)*(r2-rA2);
			}
		}
		
		return sigmaxy/(Math.pow(sigmax, 1/2)*Math.pow(sigmay, 1/2));
	}
}
